/* 新增 user */
use actix_web::cookie::ParseError::Utf8Error;
use rusqlite::{Connection, Error, Params, Result, Statement, Transaction};

use lipo_base::ltools::{lrand::rand_uuid, ltime};

use crate::lbean::user::UserTabBean;
use crate::ldb::{sql_const};


pub(crate) fn user_add(conn:  Option<&Connection>, trans: Option<&Transaction>, param: UserTabBean) -> Result<()> {
    let uuid = rand_uuid();
    let create_time = ltime::get_system_time();

    let param = (
        uuid, &param.name, &param.nickname, &param.phone, &param.id_number,
        &param.password, &param.header_img, &param.user_state, create_time
    );

    if let Some(c) = conn {
        c.execute(sql_const::USER_INSERT, param)?;
    }else if  let Some(t) = trans {
        t.execute(sql_const::USER_INSERT, param)?;
    }else {
        return Err(Error::InvalidParameterName("缺少驱动，查询失败。".to_string()));
    }

    Ok(())
}

/* 删除 */
pub(crate) fn user_delete(trx: &Transaction,  uuid: String) -> Result<()> {
    trx.execute(sql_const::USER_DELETE,
                (uuid,),
    )?;
    Ok(())
}


/* 修改密码 */
pub(crate) fn user_update_password(trx: &Transaction, uuid: String, password: String) -> Result<()> {
    trx.execute(sql_const::USER_UPDATE_PASSWORD,
                (password, uuid,),
    )?;
    Ok(())
}

/* 修改密码 */
pub(crate) fn user_update_state(trx: &Transaction, uuid: String, user_state: u8) -> Result<()> {
    trx.execute(sql_const::USER_UPDATE_STATE,
                (user_state, uuid,),
    )?;
    Ok(())
}

/* user 解析 */
fn user_select_jx(stmt: &mut Statement, param: impl Params) -> Result<Vec<UserTabBean>> {
    let person_iter = stmt.query_map(param, |row| {
        Ok(UserTabBean {
            id: row.get(0)?,
            name: row.get(1)?,
            nickname: row.get(2)?,
            phone: row.get(3)?,
            password: row.get(4)?,
            id_number: row.get(5)?,
            header_img: row.get(6)?,
            user_state: row.get(7)?,
            token: "".to_string(),
            create_time: row.get(8)?,
        })
    })?;
    let mut user_vec = Vec::new();
    for p in person_iter {
        user_vec.push(p?)
    }
    Ok(user_vec)
}

/* 查询全部 */
pub(crate) fn user_select_all(conn: &Connection) -> Result<Vec<UserTabBean>> {
    let mut stmt = conn.prepare(sql_const::USER_SELECT_ALL)?;
    return user_select_jx(&mut stmt, []);
}

/* 根据id查询 */
pub(crate) fn user_select_by_id(conn: &Connection, id: String) -> Result<Vec<UserTabBean>> {
    let mut stmt = conn.prepare(sql_const::USER_SELECT_BY_ID)?;
    return user_select_jx(&mut stmt, [id]);
}

/* 根据手机号查询 */
pub(crate) fn user_select_by_phone(conn: &Connection, phone: &String) -> Result<Vec<UserTabBean>> {
    let mut stmt = conn.prepare(sql_const::USER_SELECT_BY_PHONE)?;
    return user_select_jx(&mut stmt, [format!("%{}%",phone)]);
}































